import { Component } from '@angular/core';
import {IonicPage, NavController, NavParams, ViewController} from 'ionic-angular';
import {WorkerProvider} from "@providers/interface/worker";
import {StorageProvider} from "@providers/storage";
import {DialogProvider} from "@providers/dialog";
import {Util} from "@providers/util";

/**
 * Generated class for the WorkerMaterielReturnToPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-worker-materiel-return-to',
  templateUrl: 'worker-materiel-return-to.html',
})
export class WorkerMaterielReturnToPage {

  query_field:any = "";//查询条件
  userInfo: any = this.storage.read('userInfo');
  allPros: any[] = [];//当前库存辅材
  choosePros: any[] = this.navParams.get('choosePros');//选中的辅材
  sum: number = 0;//选中辅材的总价
  num: number = 0;//选中辅材的个数
  isClick: boolean = false;//Popover是否显示
  LLBJ:any=this.navParams.data; //领料标记

  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              public viewCtrl:ViewController,
              private worker:WorkerProvider,
              private storage:StorageProvider,
              private dialog:DialogProvider) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad WorkerMaterielReturnToPage');
    this.query();
  }

  dismiss(data?: any) {
    if (data) {
      this.viewCtrl.dismiss(data);
      return;
    }
    this.viewCtrl.dismiss();
  }

  //失去焦点查询
  sJq() {
    if (!Util.isNull(this.query_field)) {
      this.query();
    }
  }

  //点击enter查询
  shuRus(event) {
    if (event.keyCode == 13) {
      this.query();
    }
  }

  query() {
    console.log(this.query_field);
    this.worker.getSFKDC({
      'SPID': "",
      'SPMC': this.query_field,
      "partyId": this.userInfo.PARTYID
    }).then( message => {
        this.allPros = message.data;
        this.allPros.forEach(value => {
          console.log("value:" + value);
          value.QUANTITY = 0;
        });
        this.calculateChoose();
      }).catch( error => {
        alert(JSON.stringify(error));
        this.dialog.showAlert("请检查网络");
      });
  }

  /**
   * 格式化选中的辅材，并计算个数和总费用
   */
  calculateChoose() {
    //获取所有的数量不为0的辅材
    let temp = [];
    this.allPros.forEach(value => {
        temp.push(value);
    });
    this.allPros=this.allPros.filter(value => {
      return value.PJSL > 0;
    });
    this.choosePros = temp.filter(value => {
      return value.QUANTITY > 0;
    });
    //计算数量不为0的辅材的个数和总价
    this.sum = 0;
    this.num = 0;
    this.choosePros.forEach(value => {
      this.sum = +(this.sum+ +(value.PRICE * value.QUANTITY).toFixed(2)).toFixed(2);
      this.num = +(this.num+ +value.QUANTITY).toFixed(2);
    });
    if (this.num == 0) {
      this.isClick = false;
    }

  }

  /**
   * 辅材数量改变点击事件
   * @param pro 选中的商品
   * @param index 为0时表示减小，为1时表示增加
   */
  quantityChange(pro: any, index?: number) {
    switch (index) {
      case 0:
        if (pro.QUANTITY == 0) return;
        pro.QUANTITY = +(pro.QUANTITY-1).toFixed(2);
        if  (pro.QUANTITY < 0){
          pro.QUANTITY = 0;
        }
        break;
      case 1:
        pro.QUANTITY = +(+pro.QUANTITY+1).toFixed(2);
        break;
    }
    this.calculateChoose();
  }

//失去焦点改变辅材数量
  eqc(pro: any) {
    this.editChange(pro);
  }

  //点击enter改变辅材数量
  kdqc(event, pro: any) {
    if (event.keyCode == 13) {
      this.editChange(pro);
    }
  }

  editChange(pro: any) {
    this.allPros.forEach(val => {
        if (val.ZJ == pro.ZJ) {
          if (pro.QUANTITY == null) {
            val.QUANTITY = 0;
            pro.QUANTITY = 0;
          } else {
            pro.QUANTITY = +pro.QUANTITY.toFixed(2);
            if (pro.QUANTITY < 0) {
              pro.QUANTITY = 0;
            }
            val.QUANTITY = pro.QUANTITY;
          }
        }
      });
    this.calculateChoose();
  }

  /**
   * 清空选中的辅材
   */
  clearAll() {
    this.dialog.showConfirm(() => {
      this.choosePros.forEach(value => {
        value.QUANTITY = 0;
      });
      this.calculateChoose();
    }, "是否清空所有已选中的辅材！");
  }

  /**
   * 确定按钮点击事件
   */
  onSubmit() {
    this.choosePros = this.choosePros.filter(value => {
      return value.QUANTITY > 0;
    });
    if(Util.isNull(this.choosePros)){
      return this.dialog.showAlert("请选择物料");
    }
    this.worker.insertParts({
      "LLBJ":this.LLBJ,
      "materialCosts": this.choosePros,
      "SUM": this.sum,
      "partyId": this.userInfo['PARTYID']
    }).then(v => {
      this.dialog.showAlert('物料退还申请成功');
      this.dismiss();
    }).catch(e => {
    });
  }
}
